﻿using Learun.Application.Base.AuthorizeModule;
using Learun.Util;
using Learun.Util.Operat;
using System.Web.Mvc;

namespace Learun.Application.Web
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：-框架开发组
    /// 日 期：2017.03.08
    /// 描 述：登录认证（会话验证组件）
    /// </summary>
    public class HandlerLoginAttribute : AuthorizeAttribute
    {
        private DataAuthorizeIBLL dataAuthorizeIBLL = new DataAuthorizeBLL();
        private FilterMode _customMode;
        private bool IsApp = false;
        /// <summary>默认构造</summary>
        /// <param name="Mode">认证模式</param>
        public HandlerLoginAttribute(FilterMode Mode, bool isApp = false)
        {
            _customMode = Mode;
            IsApp = isApp;
        }
        /// <summary>
        /// 响应前执行登录验证,查看当前用户是否有效 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // 登录拦截是否忽略
            if (_customMode == FilterMode.Ignore)
            {
                return;
            }

            var request = filterContext.HttpContext.Request;
            string account = "", ProjectId = "";
            if (!request.Headers["account"].IsEmpty())
            {
                account = request.Headers["account"].ToString();
            }
            if (!request.QueryString["ProjectId"].IsEmpty())
            {
                ProjectId = request.QueryString["ProjectId"].ToString();
            }

            var areaName = filterContext.RouteData.DataTokens["area"] + "/";            //获取当前区域
            var controllerName = filterContext.RouteData.Values["controller"] + "/";    //获取控制器
            var action = filterContext.RouteData.Values["Action"];                      //获取当前Action
            string currentUrl = "/" + areaName + controllerName + action;               //拼接构造完整url
            //地理信息 设计模型   地址模型
            if ((filterContext.RouteData.Values["controller"].ToString() == "ProjectProcess" || filterContext.RouteData.Values["controller"].ToString() == "ManageProjectProcess" || filterContext.RouteData.Values["controller"].ToString() == "GIS"|| filterContext.RouteData.Values["controller"].ToString() == "Design"|| filterContext.RouteData.Values["controller"].ToString() == "ModelFile") && (action.ToString() == "Index" || action.ToString() == "ManageIndex"))
            {
                currentUrl = request.RawUrl;
            }
            WebHelper.AddHttpItems("currentUrl", currentUrl);

            var _currentUrl = WebHelper.GetHttpItems("currentUrl");
            if (_currentUrl.IsEmpty())
            {
                WebHelper.AddHttpItems("currentUrl", currentUrl);
            }
            else
            {
                WebHelper.UpdateHttpItem("currentUrl", currentUrl);
            }

            string loginUrl = WebHelper.HtmlDecode(WebHelper.GetCookie("LoginUrl"));
            if (string.IsNullOrEmpty(loginUrl))
            {
                loginUrl = "/Login/Index";
            }
            // 验证登录状态
            int res = OperatorHelper.Instance.IsOnLine(account, ProjectId).stateCode;
            if (res != 1)
            {
                string errorInfo = "nologin";
                switch (res)
                {
                    case 2:
                        errorInfo = "other"; //其他用户登录
                        break;
                    case 0:
                        errorInfo = "timeout";//登录过期
                        break;
                }

                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.nologin, info = errorInfo }.ToJson() };
                }
                else
                {
                    if (IsApp)
                    {
                        filterContext.Result = new RedirectResult("~/AppLogin/Index");
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("~/Login/Index?error="+ errorInfo);
                    }
                }
                return;
            }
            // IP过滤
            if (!this.FilterIP())
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.nologin, info = "noip" }.ToJson() };
                }
                else
                {
                    if (IsApp)
                    {
                        filterContext.Result = new RedirectResult("~/AppLogin/Index");
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("~/Login/Index?error=ip");
                    }
                }
                return;
            }
            // 时段过滤
            if (!this.FilterTime())
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.nologin, info = "notime" }.ToJson() };
                }
                else
                {
                    if (IsApp)
                    {
                        filterContext.Result = new RedirectResult("~/AppLogin/Index");
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("~/Login/Index?error=time");
                    }
                }
                return;
            }

            #region add by chenkai 20210323 强制跳转到重置密码页
            if (action != null && action.ToString().ToLower() != "passwordupdate" && !filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                UserInfo loginUserInfo = LoginUserInfo.Get();
                if (loginUserInfo != null && loginUserInfo.PasswordUpdateTime == null)
                {
                    filterContext.Result = new RedirectResult("~/UserCenter/PassWordUpdate");
                }
            }
            #endregion

            // 判断当前接口是否需要加载数据权限
            if (!this.DataAuthorize(currentUrl))
            {
                filterContext.Result = new ContentResult { Content = new ResParameter { code = ResponseCode.fail, info = "没有该数据权限" }.ToJson() };
                return;
            }
        }
        /// <summary>
        /// IP过滤
        /// </summary>
        /// <returns></returns>
        private bool FilterIP()
        {
            bool isFilterIP = Config.GetValue("FilterIP").ToBool();
            if (isFilterIP == true)
            {
                return new FilterIPBLL().FilterIP();
            }
            return true;
        }
        /// <summary>
        /// 时段过滤
        /// </summary>
        /// <returns></returns>
        private bool FilterTime()
        {
            bool isFilterIP = Config.GetValue("FilterTime").ToBool();
            if (isFilterIP == true)
            {
                return new FilterTimeBLL().FilterTime();
            }
            return true;
        }
        /// <summary>
        /// 执行权限认证
        /// </summary>
        /// <param name="currentUrl">当前连接</param>
        /// <returns></returns>
        private bool DataAuthorize(string currentUrl)
        {
            return dataAuthorizeIBLL.SetWhereSql(currentUrl, false);
        }
    }
}